<template>
  <div class="doctor-schedule-view">
    <h2>医生排班</h2>
    <div class="search-bar">
      <el-button-group>
        <el-button :type="currentWeekType === -1 ? 'primary' : 'default'" @click="changeWeek(-1)">上一周</el-button>
        <el-button :type="currentWeekType === 0 ? 'primary' : 'default'" @click="changeWeek(0)">本周</el-button>
        <el-button :type="currentWeekType === 1 ? 'primary' : 'default'" @click="changeWeek(1)">下一周</el-button>
      </el-button-group>
      <el-cascader
        v-model="departmentValue"
        :options="departmentOptions"
        :props="{ checkStrictly: true, emitPath: true, value: 'value', label: 'label', children: 'children' }"
        clearable
        placeholder="请选择科室"
        style="width: 160px; margin-left: 16px;"
        @change="onDepartmentChange"
      />
      <el-input v-model="searchForm.DoctorName" placeholder="请输入医生姓名" style="width: 180px; margin-left: 16px;"
        clearable />
      <el-button type="primary" @click="onSearch" style="margin-left: 16px;">搜索</el-button>
    </div>
    <el-table :data="tableRows" style="width: 100%; margin-top: 16px;" border>
      <el-table-column prop="doctorName" label="医生姓名" fixed>
        <template #default="scope">
          <span style="color:#1976d2; cursor:pointer;">{{ scope.row.doctorName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="departmentName" label="科室" fixed />
      <el-table-column v-for="(day, idx) in weekDays" :key="day.date" :label="day.label">
        <el-table-column label="上午">
          <template #default="scope">
            <span v-html="renderCell(scope.row, day.date, 0)"></span>
          </template>
        </el-table-column>
        <el-table-column label="下午">
          <template #default="scope">
            <span v-html="renderCell(scope.row, day.date, 1)"></span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="操作" width="80" fixed="right">
        <template #default="scope">
          <el-button @click="showDetail(scope.row)" circle size="small"
            style="color:#1976d2; border:none; background:transparent;">
            <el-icon>
              <Setting />
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 16px; text-align: right;">
      <el-pagination v-model:current-page="page.Index" v-model:page-size="page.Size" :total="page.TotaCount"
        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" @current-change="onPageChange"
        @size-change="onSizeChange" />
    </div>
    <!-- 排班详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" width="900px"
      :title="detailDoctor?.doctorName + (editMode ? '医生排班设置' : '医生排班详情')" class="schedule-detail-dialog">
      <template #header>
        <span>{{ detailDoctor?.doctorName }} 医生排班{{ editMode ? '设置' : '详情' }}</span>
        <div style="float:right;">
          <el-button type="primary" size="small" @click="enterEditMode" v-if="!editMode">设置排班</el-button>
          <el-button size="small" style="margin-left:8px;" @click="onCloseReserve">关闭预约</el-button>
          <el-button type="primary" size="small" @click="saveSchedule" v-if="editMode"
            style="margin-left:8px;">保存设置</el-button>
        </div>
      </template>
      <div class="detail-container">
        <div class="detail-left">
          <div class="doctor-title">{{ detailDoctor?.doctorName }} 医生排班{{ editMode ? '设置' : '详情' }}</div>
          <div class="detail-date">{{ detailSelectedDate.format('YYYY年M月D日') }}<br>{{
            weekNames[detailSelectedDate.day()] }}
          </div>
          <template v-if="!editMode">
            <div class="detail-section">
              <div>上午</div>
              <div>接诊时间：{{ getDetailCell(detailSelectedDate, 1)?.startTime ? moment(getDetailCell(detailSelectedDate,
                1)?.startTime).format('HH:mm') : '--' }}-{{ getDetailCell(detailSelectedDate, 1)?.endTime ?
                  moment(getDetailCell(detailSelectedDate, 1)?.endTime).format('HH:mm') : '--' }}</div>
              <div>号源数：{{ getDetailCell(detailSelectedDate, 1)?.slotCount ?? '-' }}</div>
              <div>接诊人数：{{ getDetailCell(detailSelectedDate, 1)?.appointmentCount ?? '-' }}</div>
            </div>
            <div class="detail-section">
              <div>下午</div>
              <div>接诊时间：{{ getDetailCell(detailSelectedDate, 2)?.startTime ? moment(getDetailCell(detailSelectedDate,
                2)?.startTime).format('HH:mm') : '--' }}-{{ getDetailCell(detailSelectedDate, 2)?.endTime ?
                  moment(getDetailCell(detailSelectedDate, 2)?.endTime).format('HH:mm') : '--' }}</div>
              <div>号源数：{{ getDetailCell(detailSelectedDate, 2)?.slotCount ?? '-' }}</div>
              <div>接诊人数：{{ getDetailCell(detailSelectedDate, 2)?.appointmentCount ?? '-' }}</div>
            </div>
          </template>
          <template v-else>
            <div class="detail-section">
              <div style="display:flex;align-items:center;justify-content:space-between;">
                <span>上午</span>
                <el-switch v-model="editForm.am.isAvailable" active-text="接诊" inactive-text="休息"
                  :disabled="!editMode" />
              </div>
              <el-form :model="editForm.am" label-width="0" style="margin-top:8px;">
                <el-form-item>
                  <el-time-picker
                    v-model="editForm.am.startTime"
                    :disabled="!editMode || !editForm.am.isAvailable"
                    placeholder="请选择开始时间"
                    style="width:100%;margin-bottom:4px;"
                    format="HH:mm"
                    :max-time="editForm.am.endTime"
                    clearable
                  />
                </el-form-item>
                <el-form-item>
                  <el-time-picker
                    v-model="editForm.am.endTime"
                    :disabled="!editMode || !editForm.am.isAvailable"
                    placeholder="请选择结束时间"
                    style="width:100%;margin-bottom:4px;"
                    format="HH:mm"
                    :min-time="editForm.am.startTime"
                    clearable
                  />
                </el-form-item>
                <el-form-item>
                  <el-input v-model.number="editForm.am.slotCount" :disabled="!editMode || !editForm.am.isAvailable"
                    placeholder="号源数" type="number" min="1" style="width:100%;" />
                </el-form-item>
              </el-form>
            </div>
            <div class="detail-section">
              <div style="display:flex;align-items:center;justify-content:space-between;">
                <span>下午</span>
                <el-switch v-model="editForm.pm.isAvailable" active-text="接诊" inactive-text="休息"
                  :disabled="!editMode" />
              </div>
              <el-form :model="editForm.pm" label-width="0" style="margin-top:8px;">
                <el-form-item>
                  <el-time-picker
                    v-model="editForm.pm.startTime"
                    :disabled="!editMode || !editForm.pm.isAvailable"
                    placeholder="请选择开始时间"
                    style="width:100%;margin-bottom:4px;"
                    format="HH:mm"
                    :max-time="editForm.pm.endTime"
                    clearable
                  />
                </el-form-item>
                <el-form-item>
                  <el-time-picker
                    v-model="editForm.pm.endTime"
                    :disabled="!editMode || !editForm.pm.isAvailable"
                    placeholder="请选择结束时间"
                    style="width:100%;margin-bottom:4px;"
                    format="HH:mm"
                    :min-time="editForm.pm.startTime"
                    clearable
                  />
                </el-form-item>
                <el-form-item>
                  <el-input v-model.number="editForm.pm.slotCount" :disabled="!editMode || !editForm.pm.isAvailable"
                    placeholder="号源数" type="number" min="1" style="width:100%;" />
                </el-form-item>
              </el-form>
            </div>
          </template>
        </div>
        <div class="detail-right">
          <el-date-picker v-model="detailMonth" type="month" placeholder="请选择月份" style="margin-bottom: 12px;"
            @change="onDetailMonthChange" />
          <div class="calendar-grid">
            <div v-for="cell in calendarCells" :key="cell.date.format('YYYY-MM-DD')"
              :class="['calendar-cell', { active: cell.isActive }]" @click="selectDetailDate(cell.date)">
              <div>{{ cell.day }}</div>
              <div v-if="cell.status === 'work'" style="color:#1976d2">号源 {{ cell.slotCount }}</div>
              <div v-else-if="cell.status === 'rest'" style="color:#aaa">休息</div>
              <div v-else style="color:#ccc">未排班</div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 关闭预约确认弹窗 -->
    <el-dialog v-model="closeDialogVisible" width="400px" :show-close="false" align-center>
      <div style="text-align:center;padding:24px 0;">
        <el-icon style="font-size:48px;color:#409EFF;margin-bottom:12px;"><QuestionFilled /></el-icon>
        <div style="font-size:20px;font-weight:bold;margin-bottom:8px;">关闭预约确认</div>
        <div style="color:#666;margin-bottom:24px;">关闭后该医生所有的排班将失效，用户将无法从小程序进行预约，确定关闭吗？</div>
        <el-button @click="closeDialogVisible=false" style="margin-right:16px;">取消</el-button>
        <el-button type="primary" @click="confirmCloseReserve">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import moment from 'moment'
import type { Moment } from 'moment'
import { Setting, QuestionFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { axiosrmedical } from '@/http/axiosRead'
import { axioswmedical } from '@/http/axiosWrtie'

const weekNames = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

const page = reactive({
  Index: 1,
  Size: 10,
  TotaCount: 0,
  TotaPage: 0
})

const searchForm = reactive({
  DepartmentId: undefined,
  DoctorName: '',
  WeekStart: '',
  WeekEnd: ''
})

const weekOffset = ref(0)
const rawData = ref<any[]>([])
const currentWeekType = ref(0) // -1: 上一周, 0: 本周, 1: 下一周

function getWeekRange(offset = 0) {
  // 以周一为一周的开始
  const start = moment().add(offset, 'week').startOf('isoWeek')
  const end = moment().add(offset, 'week').endOf('isoWeek')
  return {
    start: start.format('YYYY-MM-DD'),
    end: end.format('YYYY-MM-DD')
  }
}

const weekDays = computed(() => {
  const start = moment(searchForm.WeekStart)
  return Array.from({ length: 7 }).map((_, i) => {
    const date = start.clone().add(i, 'day')
    const weekLabel = weekNames[date.day()]
    return {
      date: date.format('YYYY-MM-DD'),
      label: date.format('YYYY/MM/DD') + ' ' + weekLabel
    }
  })
})

function changeWeek(type: number) {
  if (type < -1 || type > 1) return // 只允许三种状态
  currentWeekType.value = type
  weekOffset.value = type
  const { start, end } = getWeekRange(type)
  searchForm.WeekStart = start
  searchForm.WeekEnd = end
  page.Index = 1
  fetchData()
}

function onSearch() {
  page.Index = 1
  fetchData()
}

function onPageChange(val: number) {
  page.Index = val
  fetchData()
}

function onSizeChange(val: number) {
  page.Size = val
  page.Index = 1
  fetchData()
}

function fetchData() {
  axiosrmedical.get('/DoctorSchedule/GetDoctorSchedule', {
    params: {
      PageIndex: page.Index,
      PageSize: page.Size,
      DepartmentId: searchForm.DepartmentId,
      DoctorName: searchForm.DoctorName,
      WeekStart: searchForm.WeekStart,
      WeekEnd: searchForm.WeekEnd
    }
  }).then(res => {
    rawData.value = res.data.pageData || []
    page.TotaCount = res.data.totaCount || 0
    page.TotaPage = res.data.totaPage || 0
  })
}

// 处理表格行数据
const tableRows = computed(() => {
  // 按医生id+科室分组
  const map = new Map<string, any>()
  for (const item of rawData.value) {
    const key = `${item.doctorId}_${item.departmentId}`
    if (!map.has(key)) {
      map.set(key, {
        doctorId: item.doctorId,
        doctorName: item.doctorName,
        departmentId: item.departmentId,
        departmentName: item.departmentName,
        scheduleMap: {} // { '2024-07-01_0': {isAvailable, appointmentCount, slotCount} }
      })
    }
    const row = map.get(key)
    const day = moment(item.scheduleDate).format('YYYY-MM-DD')
    row.scheduleMap[`${day}_${item.period}`] = item
  }
  return Array.from(map.values())
})

function renderCell(row: any, date: string, period: number) {
  const realPeriod = period + 1 // 0=>1, 1=>2
  const key = `${date}_${realPeriod}`
  const item = row.scheduleMap[key]
  if (!item) return '<span style="color:#bbb">休</span>'
  if (!item.isAvailable) return '<span style="color:#bbb">休</span>'
  // 预约数量为红色，斜杠后黑色
  return `<span><span style='color:red'>${item.appointmentCount}</span>/<span style='color:black'>${item.slotCount}</span></span>`
}

// 详情弹窗相关
const detailDialogVisible = ref(false)
const detailDoctor = ref<any>(null)
const detailMonth = ref(moment())
const detailSelectedDate = ref(moment())
const detailSchedules = ref<any[]>([])

function showDetail(row: any) {
  detailDoctor.value = row
  detailMonth.value = moment()
  detailSelectedDate.value = moment()
  fetchDoctorMonthSchedule(row.doctorId, row.departmentId, detailMonth.value)
  detailDialogVisible.value = true
  editMode.value = false // 每次打开先为详情模式
}

function fetchDoctorMonthSchedule(doctorId: number, departmentId: number, month: Moment) {
  // 假设接口同 GetDoctorSchedule，按月取数据
  axiosrmedical.get('/DoctorSchedule/GetDoctorSchedule', {
    params: {
      PageIndex: 1,
      PageSize: 100,
      DepartmentId: departmentId,
      DoctorName: detailDoctor.value.doctorName,
      WeekStart: month.clone().startOf('month').format('YYYY-MM-DD'),
      WeekEnd: month.clone().endOf('month').format('YYYY-MM-DD')
    }
  }).then(res => {
    detailSchedules.value = res.data.pageData || []
  })
}

function onDetailMonthChange(val: any) {
  fetchDoctorMonthSchedule(detailDoctor.value.doctorId, detailDoctor.value.departmentId, moment(val))
}

function selectDetailDate(date: Moment) {
  detailSelectedDate.value = moment(date)
}

const calendarCells = computed(() => {
  // 生成当前月日历
  const daysInMonth = detailMonth.value.daysInMonth()
  const cells = []
  for (let i = 1; i <= daysInMonth; i++) {
    const date = detailMonth.value.clone().date(i)
    const foundAm = detailSchedules.value.find(s => moment(s.scheduleDate).isSame(date, 'day') && s.period === 1)
    const foundPm = detailSchedules.value.find(s => moment(s.scheduleDate).isSame(date, 'day') && s.period === 2)
    let status = 'none', slotCount = 0
    if (foundAm || foundPm) {
      if ((foundAm && foundAm.isAvailable) || (foundPm && foundPm.isAvailable)) {
        status = 'work'
        slotCount = (foundAm?.slotCount || 0) + (foundPm?.slotCount || 0)
      } else {
        status = 'rest'
      }
    }
    cells.push({
      date,
      day: i,
      status,
      slotCount,
      isActive: date.isSame(detailSelectedDate.value, 'day')
    })
  }
  return cells
})

function getDetailCell(date: Moment, period: number) {
  return detailSchedules.value.find(s => moment(s.scheduleDate).isSame(date, 'day') && s.period === period)
}

const editMode = ref(false)
// 更新editForm的类型定义
interface TimeSchedule {
  isAvailable: boolean;
  startTime: string | Date;
  endTime: string | Date;
  slotCount: number;
}

const editForm = reactive({
  am: { isAvailable: true, startTime: '', endTime: '', slotCount: 20 } as TimeSchedule,
  pm: { isAvailable: true, startTime: '', endTime: '', slotCount: 20 } as TimeSchedule
})

// 生成半小时步长时间段
function genTimes(start: number, end: number) {
  const arr: string[] = [];
  for (let h = start; h <= end; h++) {
    for (let m = 0; m < 60; m += 30) {
      if (h === end && m > 0) break;
      arr.push(`${h.toString().padStart(2, '0')}:${m === 0 ? '00' : '30'}`);
    }
  }
  return arr;
}
const amTimes = genTimes(1, 12);
const pmTimes = genTimes(12, 24);

function enterEditMode() {
  editMode.value = true;
  // 反填上午
  const am = getDetailCell(detailSelectedDate.value, 1);
  editForm.am.isAvailable = am ? am.isAvailable : true;
  
  // 根据已有数据设置时间
  if (am && am.startTime) {
    const momentTime = moment(am.startTime);
    const today = new Date();
    today.setHours(momentTime.hours(), momentTime.minutes(), 0, 0);
    editForm.am.startTime = today;
  } else {
    const today = new Date();
    today.setHours(8, 0, 0, 0);
    editForm.am.startTime = today;
  }
  
  if (am && am.endTime) {
    const momentTime = moment(am.endTime);
    const today = new Date();
    today.setHours(momentTime.hours(), momentTime.minutes(), 0, 0);
    editForm.am.endTime = today;
  } else {
    const today = new Date();
    today.setHours(12, 0, 0, 0);
    editForm.am.endTime = today;
  }
  
  editForm.am.slotCount = am ? am.slotCount : 20;
  
  // 反填下午
  const pm = getDetailCell(detailSelectedDate.value, 2);
  editForm.pm.isAvailable = pm ? pm.isAvailable : true;
  
  if (pm && pm.startTime) {
    const momentTime = moment(pm.startTime);
    const today = new Date();
    today.setHours(momentTime.hours(), momentTime.minutes(), 0, 0);
    editForm.pm.startTime = today;
  } else {
    const today = new Date();
    today.setHours(13, 0, 0, 0);
    editForm.pm.startTime = today;
  }
  
  if (pm && pm.endTime) {
    const momentTime = moment(pm.endTime);
    const today = new Date();
    today.setHours(momentTime.hours(), momentTime.minutes(), 0, 0);
    editForm.pm.endTime = today;
  } else {
    const today = new Date();
    today.setHours(17, 0, 0, 0);
    editForm.pm.endTime = today;
  }
  
  editForm.pm.slotCount = pm ? pm.slotCount : 20;
}

function saveSchedule() {
  // 校验时间有效性
  const validateTimes = () => {
    // 检查上午时段
    if (editForm.am.isAvailable) {
      if (!editForm.am.startTime || !editForm.am.endTime) {
        ElMessage.warning('请设置上午时段的开始和结束时间');
        return false;
      }
      
      const amStartTime = typeof editForm.am.startTime === 'string' ? 
        moment(editForm.am.startTime, 'HH:mm') : 
        moment(editForm.am.startTime);
        
      const amEndTime = typeof editForm.am.endTime === 'string' ? 
        moment(editForm.am.endTime, 'HH:mm') : 
        moment(editForm.am.endTime);
        
      if (amStartTime.isAfter(amEndTime)) {
        ElMessage.warning('上午时段的开始时间不能晚于结束时间');
        return false;
      }
    }
    
    // 检查下午时段
    if (editForm.pm.isAvailable) {
      if (!editForm.pm.startTime || !editForm.pm.endTime) {
        ElMessage.warning('请设置下午时段的开始和结束时间');
        return false;
      }
      
      const pmStartTime = typeof editForm.pm.startTime === 'string' ? 
        moment(editForm.pm.startTime, 'HH:mm') : 
        moment(editForm.pm.startTime);
        
      const pmEndTime = typeof editForm.pm.endTime === 'string' ? 
        moment(editForm.pm.endTime, 'HH:mm') : 
        moment(editForm.pm.endTime);
        
      if (pmStartTime.isAfter(pmEndTime)) {
        ElMessage.warning('下午时段的开始时间不能晚于结束时间');
        return false;
      }
    }
    
    return true;
  };
  
  // 如果校验不通过，直接返回
  if (!validateTimes()) {
    return;
  }

  // 解析时间并将本地时间直接转为ISO字符串，不进行时区转换
  let amStartHour, amStartMinute, amEndHour, amEndMinute;
  let pmStartHour, pmStartMinute, pmEndHour, pmEndMinute;
  
  // 处理上午时间
  if (typeof editForm.am.startTime === 'string') {
    // 如果是字符串格式 (HH:mm)
    const parts = editForm.am.startTime.split(':');
    amStartHour = Number(parts[0]);
    amStartMinute = Number(parts[1]);
  } else if (editForm.am.startTime) {
    // 如果是Date对象
    amStartHour = editForm.am.startTime.getHours();
    amStartMinute = editForm.am.startTime.getMinutes();
  } else {
    // 默认值
    amStartHour = 8;
    amStartMinute = 0;
  }
  
  if (typeof editForm.am.endTime === 'string') {
    const parts = editForm.am.endTime.split(':');
    amEndHour = Number(parts[0]);
    amEndMinute = Number(parts[1]);
  } else if (editForm.am.endTime) {
    amEndHour = editForm.am.endTime.getHours();
    amEndMinute = editForm.am.endTime.getMinutes();
  } else {
    amEndHour = 12;
    amEndMinute = 0;
  }
  
  // 处理下午时间
  if (typeof editForm.pm.startTime === 'string') {
    const parts = editForm.pm.startTime.split(':');
    pmStartHour = Number(parts[0]);
    pmStartMinute = Number(parts[1]);
  } else if (editForm.pm.startTime) {
    pmStartHour = editForm.pm.startTime.getHours();
    pmStartMinute = editForm.pm.startTime.getMinutes();
  } else {
    pmStartHour = 13;
    pmStartMinute = 0;
  }
  
  if (typeof editForm.pm.endTime === 'string') {
    const parts = editForm.pm.endTime.split(':');
    pmEndHour = Number(parts[0]);
    pmEndMinute = Number(parts[1]);
  } else if (editForm.pm.endTime) {
    pmEndHour = editForm.pm.endTime.getHours();
    pmEndMinute = editForm.pm.endTime.getMinutes();
  } else {
    pmEndHour = 17;
    pmEndMinute = 0;
  }
  
  // 创建日期对象并设置为当地时间
  const baseDate = detailSelectedDate.value.format('YYYY-MM-DD');
  const amStartTimeStr = `${baseDate}T${amStartHour.toString().padStart(2, '0')}:${amStartMinute.toString().padStart(2, '0')}:00+08:00`;
  const amEndTimeStr = `${baseDate}T${amEndHour.toString().padStart(2, '0')}:${amEndMinute.toString().padStart(2, '0')}:00+08:00`;
  const pmStartTimeStr = `${baseDate}T${pmStartHour.toString().padStart(2, '0')}:${pmStartMinute.toString().padStart(2, '0')}:00+08:00`;
  const pmEndTimeStr = `${baseDate}T${pmEndHour.toString().padStart(2, '0')}:${pmEndMinute.toString().padStart(2, '0')}:00+08:00`;

  const data = {
    doctorId: detailDoctor.value.doctorId,
    date: detailSelectedDate.value.format(),
    am: {
      isAvailable: editForm.am.isAvailable,
      startTime: amStartTimeStr,
      endTime: amEndTimeStr,
      slotCount: editForm.am.slotCount
    },
    pm: {
      isAvailable: editForm.pm.isAvailable,
      startTime: pmStartTimeStr,
      endTime: pmEndTimeStr,
      slotCount: editForm.pm.slotCount
    }
  }
  axioswmedical.post('/DoctorSchedule/SetDoctorDaySchedule', data).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('排班设置成功')
      editMode.value = false
      detailDialogVisible.value = false
      fetchData() // 刷新主表
    } else {
      ElMessage.error(res.data.msg || '排班设置失败')
    }
  })
}

const closeDialogVisible = ref(false)

function onCloseReserve() {
  closeDialogVisible.value = true
}

function confirmCloseReserve() {
  axioswmedical.put('/Doctor/UpdateDoctorStatus', {
    doctorId: detailDoctor.value.doctorId,
    status: false
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('已成功关闭该医生预约')
      closeDialogVisible.value = false
      detailDialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(res.data.msg || '关闭预约失败')
    }
  })
}

const departmentOptions = ref<any[]>([])
const departmentValue = ref<any[]>([])

function fetchDepartments() {
  axiosrmedical.get('/Department/GetAllDepartments').then(res => {
    if (res.data.code === 200) {
      departmentOptions.value = (res.data.data || []).map(mapDepartment)
    }
  })
}
function mapDepartment(dep: any) {
  return {
    value: dep.id,
    label: dep.departmentName,
    children: Array.isArray(dep.children) ? dep.children.map(mapDepartment) : undefined
  }
}
function onDepartmentChange(val: any[]) {
  searchForm.DepartmentId = val && val.length ? val[val.length - 1] : undefined
}

onMounted(() => {
  fetchDepartments()
  currentWeekType.value = 0
  weekOffset.value = 0
  const { start, end } = getWeekRange(0)
  searchForm.WeekStart = start
  searchForm.WeekEnd = end
  fetchData()
})

// expose weekNames to template
defineExpose({ weekNames })
</script>

<style scoped>
.doctor-schedule-view {
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.schedule-detail-dialog .detail-container {
  display: flex;
  gap: 24px;
}

.detail-left {
  width: 220px;
  background: #ff9800;
  color: #fff;
  border-radius: 8px;
  padding: 24px 16px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.doctor-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
}

.detail-date {
  font-size: 16px;
  margin-bottom: 16px;
}

.detail-section {
  margin-bottom: 16px;
  background: #fff3e0;
  color: #ff9800;
  border-radius: 6px;
  padding: 8px 12px;
  width: 100%;
}

.detail-right {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  min-width: 500px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8px;
}

.calendar-cell {
  background: #f5f5f5;
  border-radius: 6px;
  padding: 8px 0;
  text-align: center;
  cursor: pointer;
  color: #1976d2;
  font-weight: 500;
  transition: background 0.2s;
}

.calendar-cell.active {
  background: #1976d2;
  color: #fff;
}
</style>